﻿using SiyinPractice.Application.Core;
using SiyinPractice.Domain.Core;
using SiyinPractice.Domain.Maintenance;
using SiyinPractice.Domain.ProjectManagement.ProjectManage;
using SiyinPractice.Framework.Mapper;
using SiyinPractice.Interface.ProjectManagement.ProjectManage;
using SiyinPractice.Shared.Core.Dto;
using SiyinPractice.Shared.Core.Exceptions;
using SiyinPractice.Shared.Core.Utility;
using SiyinPractice.Shared.ProjectManagement.Dto.ProjectManage;
using SiyinPractice.Shared.ProjectManagement.Dto.ProjectManage.WXMsg;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace SiyinPractice.Application.ProjectManagement.ProjectManage
{
    public class DingDingService : NamedEntityService<DingDing, DingDingDto, DingDingSearchPagedDto, CreateDingDingDto>, IDingDingService
    {
        private IEfRepository<AccountPassword> _accountPassword;
        public DingDingService(IEfRepository<DingDing> repository, IObjectMapper objectMapper,
            IEfRepository<AccountPassword> accountPassword) : base(repository, objectMapper)
        {
            _accountPassword = accountPassword;
        }


        public override async Task<DingDingDto> AddAsync(CreateDingDingDto createInput)
        {
            Validate.Assert(createInput == null, SiyinPracticeMessage.DTO_IS_NULL);
            var exits = await Repository.AnyAsync(x => x.Name == createInput.Name);
            Validate.Assert(exits, SiyinPracticeMessage.ENTITY_EXIST, createInput.Name);
            createInput.IsPid = false;
            createInput.To_All_User = false;
            createInput.Msgtype = "text";
            return await base.AddAsync(createInput);
        }
        public override async Task<int> UpdateAsync(DingDingDto dto)
        {
            Validate.Assert(dto == null, SiyinPracticeMessage.DTO_IS_NULL);
            dto.IsPid = false;
            dto.To_All_User = false;
            dto.Msgtype = "text";
            return await base.UpdateAsync(dto);
        }

        public override async Task<int> RemoveAsync(Guid id)
        {
            var entity = await Repository.FindAsync(id);
            var exits = await _accountPassword.FindAsync(x => x.ReminderTemplate == Convert.ToString(id));
            if(exits != null)
            {
                Validate.Assert(exits != null, $"{entity.Name}模板已经被账号{exits.AccountName}使用");
            }
            Validate.Assert(entity == null, SiyinPracticeMessage.DELETE_NONEXIST);
            return await Repository.DeleteAsync(id);
        }
        public override async Task<IList<DingDingDto>> GetAllAsync()
        {
            var domains = Repository.Where(x => x.IsPid == false).ToList();
            var dtoTasks = domains.Select(x => MapToEntityDto(x));
            return await Task.WhenAll(dtoTasks);
        }
        public  async Task<int> ParentSetting(DingDingDto createInput)
        {
            
            Validate.Assert(createInput == null, SiyinPracticeMessage.DTO_IS_NULL);
          
            var exits = await Repository.AnyAsync(x => x.IsPid == true);
            if (exits)
            {
                var entity = await Repository.FindAsync(x => x.Id == createInput.Id);
                Validate.Assert(entity == null, "数据不存在");
               
                entity.Editor = Framework.Security.UserTokenService.GetUserToken().UserName;
                entity.EditTime = DateTime.Now;
                entity.Appkey = createInput.Appkey;
                entity.Appsecret = createInput.Appsecret;
                entity.Agent_id = createInput.Agent_id;
                entity.DefaultTimer = createInput.DefaultTimerInterval+60;
                entity.DefaultTimerInterval = createInput.DefaultTimerInterval;
                entity.IsPid = true;
                entity.To_All_User = false;
                return await Repository.UpdateAsync(entity);

            }
            else
            {
                var entity = await MapToEntity(createInput);
                if (entity is AuditEntity auditEntity)
                {
                    auditEntity.Creator = Framework.Security.UserTokenService.GetUserToken().UserName;
                    auditEntity.CreateTime = DateTime.Now;
                }
                entity.IsPid= true;
                entity.To_All_User = false;
                entity.DefaultTimer = createInput.DefaultTimerInterval+60;

                return await Repository.InsertAsync(entity);
            }
            
           
           
        }
        public async Task<DingDingDto> GetParentSetting()
        {
            var exits = await Repository.FindAsync(x => x.IsPid == true);
            return await MapToEntityDto(exits);
        }
        public override async Task<PageModelDto<DingDingDto>> GetPagedAsync(DingDingSearchPagedDto search)
        {
            var whereExpression = BuildWhereExpression(ExpressionCreator.New<DingDing>(), search);

            //var total = await Repository.CountAsync(whereExpression);
            //if (total == 0) return new PageModelDto<DingDingDto>(search);

            var includeProperties = BuildIncludeProperties();
            var all = Repository.Where(whereExpression, includeProperties);
            // List<DingDingDto> invoiceHistoryDtosList = new List<DingDingDto>();
            var msgReminderDtos = await MapToEntityDto(all.Where(x => x.IsPid == false).ToList());
            var entities = msgReminderDtos
                               .OrderBy(x => x.Id)
                               .Skip(search.SkipRows())
                               .Take(search.PageSize).ToList();

            return new PageModelDto<DingDingDto>(search, entities, msgReminderDtos.Count);
        }
    }
}
